package com.aaa.dao;

import org.apache.commons.dbcp2.BasicDataSource;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @version 1.0
 * @Author Lotsot
 * @Date 2023/8/23 11:17
 * @Description: 注册驱动、获取连接
 */
public class DBUtil {
    /**
     * 数据库配置属性
     */
    private static String url;
    private static String username;
    private static String password;
    private static String driver;
    private static String maxActive;
    private static String minIdle;
    private static BasicDataSource dataSource;

    /**
     * @description: 加载配置、注册驱动
     * @create time 2023/8/30 15:04
     * @param null
     * @return
     */
    static {
        //创建Properties类
        Properties pro = new Properties();
        //1.获取路径
        ClassLoader classLoader = DBUtil.class.getClassLoader();
        InputStream resourceAsStream = classLoader.getResourceAsStream("jdbc.properties");
        //2.加载文件
        try {
            pro.load(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //3.获取数据，赋值
        url = pro.getProperty("url");
        username = pro.getProperty("username");
        password = pro.getProperty("password");
        driver = pro.getProperty("driver");
        maxActive = pro.getProperty("maxActive");
        minIdle = pro.getProperty("minIdle");

        //4.初始化数据库连接池
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setMaxTotal(Integer.parseInt(maxActive));
        dataSource.setMinIdle(Integer.parseInt(minIdle));
    }

    /**
     * @return java.sql.Connection
     * @description: 获取连接
     * @create time 2023/8/30 15:05
     */
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param conn
     * @param stmt
     * @param res
     * @return void
     * @description:
     * @create time 2023/8/30 15:08
     */
    public static void close(Connection conn, Statement stmt, ResultSet res) {
        if (res != null) {
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
